import React, { Component } from 'react'

export default class States extends Component {
    constructor(props) {
        super(props)
        this.state = {
            date: new Date()
        }
    }
    
    // 挂载
    componentDidMount() {
        this.timerId = setInterval(() =>
            this.tick(), 1000
        )
    }

    // 卸载
    componentWillUnmount() {
        clearInterval(this.timerId)
    }

    tick() {
        this.setState({
            date: new Date()
        })
    }

    render() {
        return (
            <div>
                state是组件的私有属性
                <br/>
                构造函数是唯一可以给state赋值的地方
                <br/>
                不要直接修改state，而是使用setState()
                <hr />
                <div>
                    {this.state.date.toLocaleTimeString()}
                </div>
            </div>
        )
    }
}